<template>
  <div id="login-mana">
    <el-card class="login-card">
      <h2 class="title">管理员登录</h2>

      <!-- 登录表单 -->
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="0">
        <el-form-item prop="phone">
          <el-input
            v-model="form.phone"
            prefix-icon=" el-icon-phone"
            type="tel"
            placeholder="请输入手机号"
            pattern="[0-9]{11}"
            :maxlength="11"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            prefix-icon=" el-icon-lock"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleManagerLogin"
            :loading="isLoading"
            style="width: 100%"
          >
            立即登录
          </el-button>
        </el-form-item>

        <!-- 返回用户端链接（右下角） -->
        <div class="back-link" @click="goBackToUserLogin">
          <el-icon><ArrowLeft /></el-icon> 返回用户端
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getManagerBasicInfo } from "@/api/login";
import websocketServe from "@/util/manager_api/websocket-serve";
import { loginByManager } from "@/api/login";
import { Message } from "element-ui";
import { mapState, mapActions } from "vuex";
export default {
  data() {
    return {
      form: {
        phone: "",
        password: "",
      },
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效手机号",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, max: 20, message: "密码长度为4-20位", trigger: "blur" },
        ],
      },
      isLoading: false,
      isSending: false,
    };
  },

  created() {
    this.checkAndRedirect();
  },

  computed: {
    isValidPhone() {
      return /^1[3-9]\d{9}$/.test(this.form.phone);
    },

    ...mapState("manager", {
      managerUserInfo: "userInfo",
    }),
  },

  methods: {
    ...mapActions("manager", ["fetchManagerInfo", "initWebSocket"]),
    goBackToUserLogin() {
      this.$router.push("/login");
    },
    handlePhoneInput(e) {
      this.form.phone = e.target.value.replace(/[^\d]/g, "").slice(0, 11);
    },
    async handleManagerLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return;
        try {
          const response = await loginByManager(this.form);
          this.$store.commit("manager/SET_TOKEN", response.data.data);
          //初始化 WebSocket
          await this.$store.dispatch("manager/initWebSocket");
          await this.$store.dispatch("manager/fetchManagerInfo");

          this.$router.replace("/data-overview");
          Message.success("登录成功");
        } catch (error) {
          Message.error(error.msg || "登录失败");
        }
      });
    },

    async checkAndRedirect() {
      let isManagerLoggedIn = false;
      try {
        const res = await getManagerBasicInfo();
        if (res.data.code === 201) {
          isManagerLoggedIn = true;
        } else {
          this.$store.commit("manager/CLEAR_STATE");
        }
        if (this.$route.path === "/manage-login") {
          if (isManagerLoggedIn) {
            await this.$store.dispatch("manager/initWebSocket");
            // this.$router.push("/data-overview");
          }
          if (this.$route.path === "/manage-login") {
            if (isManagerLoggedIn) {
              this.$router.push("/data-overview");
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped>
@import "element-ui/lib/theme-chalk/index.css";

#login-mana {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-image: url("/public/image/登录页面背景.jpg");
  background-size: cover;
  background-position: center;
  background-color: #f0f2f5;
}

.login-card {
  padding: 30px 40px;
  width: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background-color: rgba(255, 255, 255, 0.5);
  /* 半透明背景 */
  position: relative;
  /* 用于定位内部元素 */
}

.title {
  text-align: center;
  font-size: 24px;
  color: #409eff;
  margin-bottom: 30px;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.el-input__inner {
  height: 48px;
  font-size: 16px;
}

.el-button--primary {
  height: 50px;
  font-size: 16px;
  border-radius: 8px;
}

/* 返回用户端链接（右下角） */
.back-link {
  position: absolute;
  bottom: 20px;
  right: 20px;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.back-link .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.back-link:hover {
  color: #409eff;
}
</style>